package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

// Redis工具类，解决缓存穿透与缓存击穿的问题
@Slf4j
@Component
public class CacheClient {
    @Resource
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    // 设置逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    // 解决缓存穿透问题
    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID,R> function, Long time, TimeUnit unit){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            // 2.如果有，返回
            return JSONUtil.toBean(json, type);
        }
        // 这里就是空数据
        if (json != null) {
            return null;
        }

        // 3.如果没有，用数据库查询，然后存入redis
        R r = function.apply(id);
        if (r == null) {
            // 空数据，同样存储到redis
            stringRedisTemplate.opsForValue().set(key, "", time, unit);
            return null;
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(r), time, unit);
        return r;
    }

    // 利用逻辑过期解决缓存击穿问题，同时利用存储空值解决缓存穿透问题
    public <R,ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID,R> function, Long time, TimeUnit unit, String lockKeyPrefix){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        // 进行判断，空值存储解决缓存穿透
        if(StrUtil.isBlank(json)){
            if (json != null){
                return null;
            }
            R r = function.apply(id);
            if (r == null){
                // 这里也修改成逻辑过期
                this.setWithLogicalExpire(key,"",time,unit);
                return null;
            }
            this.setWithLogicalExpire(key,r,time,unit);
        }
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        // 没有过期
        // 这里第一次进行访问时expireTime会为null并且报错，所以再加上对expireTime的判断
        if (expireTime != null && expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        // 过期
        String lockKey = lockKeyPrefix + id;
        Boolean lock = tryLock(lockKey);
        if (lock){
            // 先进行双重检查
            String jsonDouble = stringRedisTemplate.opsForValue().get(key);
            // 判断，如果jsonDouble不为空，则进一步判断是否过期，如果不过期，就直接返回，其他条件都是向下走
            if (StrUtil.isNotBlank(jsonDouble)){
                RedisData redisData1 = JSONUtil.toBean(jsonDouble, RedisData.class);
                LocalDateTime expireTime1 = redisData1.getExpireTime();
                JSONObject data1 = (JSONObject) redisData1.getData();
                R r1 = JSONUtil.toBean(data1, type);
                if(expireTime1.isAfter(LocalDateTime.now())){
                    return r1;
                }
            }
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    // 添加到数据库
                    R r1 = function.apply(id);
                    setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(key);
                }
            });
        }
        // 返回
        return r;
    }

    public <R,ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID,R> function, Long time, TimeUnit unit, String lockKeyPrefix){
        String key = keyPrefix + id;
        String lockKey = lockKeyPrefix + id;
        // 1.查询缓存，判断有没有缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            // 2.如果有，返回
            return JSONUtil.toBean(json, type);
        }
        // 这里就是空数据
        if (json != null) {
            return null;
        }
        R r;
        try {
            boolean lock = tryLock(lockKey);
            while (!lock){
                lock = tryLock(lockKey);
                Thread.sleep(10);
            }
            String doubleCheck = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(doubleCheck)){
                return JSONUtil.toBean(doubleCheck,type);
            }
            r = function.apply(id);
            if(r == null){
                stringRedisTemplate.opsForValue().set(key,"",time,unit);
                return null;
            }
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time,unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }
        return r;

    }

    private final static ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Boolean tryLock(String key) {
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
